import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:msal_auth/models/msal_exception.dart';
import 'package:msal_auth/msal_auth.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

import '../../api/interface/login_api.dart';
import '../../api/request/response_data.dart';
import '../../basic/base_info.dart';
import '../../config/const.dart';
import '../../utils/string_tool.dart';
import '../../widget/common_widget.dart';
import '../index_drawer_page.dart';
class LoginCodePage extends StatefulWidget {
  final Map arguments;
  const LoginCodePage({super.key, required this.arguments});

  @override
  State<LoginCodePage> createState() => _LoginCodePageState();
}

class _LoginCodePageState extends State<LoginCodePage> {
  String? password;
  bool isDisabled = true;
  bool isDone = false;
  TextEditingController passwordController = TextEditingController();

  Timer? _countdownTimer;
  int _countdownNum = 60;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getMsgCode();
  }

  getIsDone(){
    if( password == null || password!.isEmpty || password!.length<6 ){
      isDone = false;
    }else{
      isDone = true;
    }
    if(mounted){
      setState(() {});
    }
  }

  _login()async{
    showLoading();
    ResponseData res = await LoginAPI.gmailCodeLogin({
      'username':widget.arguments['mail'],
      'captcha':password
    });
    hideLoading();
    if(res.code == 200){
      LocalBaseInfo.setToken(res.data['token']);
      LocalBaseInfo.setAccount(widget.arguments['mail'],);
      bool updateUser = res.data['updateUser']?? true;
      if(!updateUser){
        Navigator.of(context).pushNamed('MailRegister',arguments: true);
      }else{
        Navigator.pushAndRemoveUntil(context, PageRouteBuilder(
            settings: const RouteSettings(name: "index"),
            pageBuilder:
                (BuildContext context, Animation animation,
                Animation secondaryAnimation) {
              return const DrawerIndexPage();
            }), (route) => false);
      }
    }
  }

  _loginAPPByApple()async{
    AuthorizationCredentialAppleID appleIdCredential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName
      ],
    );
    String? identityToken = appleIdCredential.identityToken;
    // final oAuthProvider = OAuthProvider('apple.com');
    print('identityToken ==user ${identityToken.toString()}');
    // final credential = oAuthProvider.credential(
    //   idToken: appleIdCredential.identityToken,
    //   accessToken: appleIdCredential.authorizationCode,
    // );
    if(identityToken != null ){
      _getCodeSignOrLogin('3',identityToken!);
    }
    // try{
    //   print('_loginAPPByApple ==user 123');
    //   final UserCredential? user = (await FirebaseAuth.instance.signInWithCredential(credential));
    //   print('_loginAPPByApple ==user ${user.toString()}');
    //   if(identityToken != null){
    //
    //   }
    // }catch(e){
    //   print('error == '+e.toString());
    // }
  }

  _loginAPPByGoogle()async{
    const List<String> scopes = <String>[
      'email',
    ];
    GoogleSignIn _googleSignIn = GoogleSignIn(
        scopes: scopes
    );
    GoogleSignInAccount? account = await _googleSignIn.signIn();

    GoogleSignInAuthentication? authentication = await account?.authentication;

    StringTool.long_p('authenticationaccessToken ==='+authentication!.accessToken.toString());
    StringTool.long_p('authenticationidToken ==='+authentication!.idToken.toString());
    if(authentication != null && authentication!.idToken != null){
      _getCodeSignOrLogin('1',authentication!.idToken!);
    }

    //  final credential =  GoogleAuthProvider.credential(accessToken: authentication?.accessToken, idToken: authentication?.idToken);
    //
    // UserCredential user = await FirebaseAuth.instance.signInWithCredential(credential);
    //
    //
    //  print('_googleSignIn ==='+user.toString());
  }

  _loginAppByMsal()async{
    // MsalMobileClient msalAuth = await MsalMobileClient.init(
    //   clientId: _clientId,
    //   scopes: _scopes,
    //   androidConfig: AndroidConfig(
    //     configFilePath: 'assets/msal_config.json',
    //     tenantId: _tenantId,
    //   ),
    //   iosConfig: IosConfig(authority: _authority),
    // );
    // try {
    //   final user = await msalAuth.acquireToken();
    //   print('User data: ${user?.toJson()}');
    // } on MsalException catch (e) {
    //   print('Msal exception with error: ${e.errorMessage}');
    // } catch (e) {
    //   print(e.toString());
    // }
    // return;
    getToken();
  }

  Future<MsalAuth> getMsalAuth() async {
    return MsalAuth.createPublicClientApplication(
      clientId: clientId,
      scopes: scopes,
      androidConfig: AndroidConfig(
        configFilePath: 'assets/msal_config.json',
        // tenantId: _tenantId
      ),
      iosConfig: IosConfig(authority: iosAuth,authMiddleware: AuthMiddleware.webView),);
  }
  Future<void> getToken() async {
    try {
      final msalAuth = await getMsalAuth();
      final user = await msalAuth.acquireToken();
      if(user != null){
        _getCodeSignOrLogin('2',user!.idToken);
      }
    } on MsalException catch (e) {
      print('Msal exception with error: ${e.errorMessage}');
    } catch (e) {
      print(e.toString());
    }
  }

  Future<void> getTokenSilently() async {
    try {
      final msalAuth = await getMsalAuth();
      final user = await msalAuth.acquireTokenSilent();
      print('User data: ${user?.toJson()}');
    } on MsalException catch (e) {
      print('Msal exception with error: ${e.errorMessage}');
    } catch (e) {
      print(e.toString());
    }
  }

  _getCodeSignOrLogin(String loginType,String token)async{
    //google,microsoft,apple
    Map<String,dynamic> data = {
      'loginType':loginType,
      'token':token
    };
    showLoading();
    ResponseData res = await LoginAPI.getCodeSignOrLogin(data);
    hideLoading();
    if(res.code == 200){
      LocalBaseInfo.setToken(res.data['token']);
      bool updateUser = res.data['updateUser']?? true;
      if(!updateUser){
        Navigator.of(context).pushNamed('MailRegister',arguments: true);
      }else{
        Navigator.pushAndRemoveUntil(context, PageRouteBuilder(
            settings: const RouteSettings(name: "index"),
            pageBuilder:
                (BuildContext context, Animation animation,
                Animation secondaryAnimation) {
              return const DrawerIndexPage();
            }), (route) => false);
      }
    }
  }

  /// 获取验证码
  void _getMsgCode() async {
    if(_countdownNum<60){
      return;
    }
    showLoading();
    ResponseData res = await LoginAPI.sendEmailLogin(widget.arguments['mail']);
    hideLoading();
    if (res.code == 200) {
      _startCountDownTimer();
    }
  }

  /// 开始倒计时
  _startCountDownTimer() {
    if(_countdownTimer != null){
      _countdownTimer?.cancel();
      _countdownTimer = null;
      _countdownNum = 60;
      if(mounted){
        setState(() {});
      }
    }
    _countdownTimer = Timer.periodic(new Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdownNum > 0) {
          _countdownNum--;
        } else {
          _countdownTimer?.cancel();
          _countdownTimer = null;
          _countdownNum = 60;
        }
      });
    });
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _countdownTimer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 48.w),
        child: GestureDetector(
          onTap: (){
            getIsDone();
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: SingleChildScrollView(
            child: Container(
              height: 1.sh,
              alignment: Alignment.center,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SizedBox(height:160.w,),
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Visibility(child: GestureDetector(
                          onTap: (){
                            FocusScope.of(context).requestFocus(FocusNode());
                            Navigator.of(context).pop();
                          },
                          child: Container(
                            child: Image.asset('assets/login/back.png',width: 56.w,),
                          ),
                        ),visible: true,),
                        SizedBox(height: 28.w,),
                        Container(
                          width: 0.8.sw,
                          child: Text('We\'ve emailed you a verification code'.tr,style: TextStyle(
                              color: Colors.white,
                              fontSize: 48.sp,
                              fontWeight: FontWeight.w600
                          ),),
                        )
                      ],
                    ),
                  ),
                  SizedBox(height: 100.w,),
                  Container(
                    alignment: Alignment.center,
                    child: Text(widget.arguments['mail'],style: TextStyle(
                        color: Colors.white,
                        fontSize: 28.sp,
                        fontWeight: FontWeight.w500
                    ),),
                  ),
                  SizedBox(height: 32.w,),
                  //密码
                  Container(
                    width: 670.w,
                    padding: EdgeInsets.symmetric(horizontal: 0.w),
                    child:  Stack(
                      children: [
                        Container(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                  border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 2.w),
                                  borderRadius: BorderRadius.circular(8.w)
                                ),
                              ),
                              Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                    border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 2.w),
                                    borderRadius: BorderRadius.circular(8.w)
                                ),
                              ),
                              Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                    border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 2.w),
                                    borderRadius: BorderRadius.circular(8.w)
                                ),
                              ),
                              Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                    border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 2.w),
                                    borderRadius: BorderRadius.circular(8.w)
                                ),
                              ),
                              Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                    border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 2.w),
                                    borderRadius: BorderRadius.circular(8.w)
                                ),
                              ),
                              Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                    border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 2.w),
                                    borderRadius: BorderRadius.circular(8.w)
                                ),
                              )
                            ],
                          ),
                        ),
                        Container(
                          width: 670.w,
                          height: 92.w,
                          child: PinCodeTextField(
                            length: 6,
                            obscureText: false,
                            animationType: AnimationType.fade,
                            scrollPadding: EdgeInsets.zero,
                            keyboardType: TextInputType.number,
                            pinTheme: PinTheme(
                              shape: PinCodeFieldShape.box,
                              borderRadius: BorderRadius.circular(6.w),
                              fieldHeight: 92.w,
                              fieldWidth: 92.w,
                              borderWidth: 2.w,
                              inactiveFillColor: Colors.transparent,
                              inactiveColor: Colors.transparent,
                              activeColor: Colors.transparent,
                              activeFillColor: Colors.transparent,
                              selectedColor: Colors.transparent,
                              selectedFillColor: Colors.transparent,
                              fieldOuterPadding: EdgeInsets.zero,
                              activeBorderWidth: 0.w,
                              inactiveBorderWidth: 0.w,
                              disabledColor: Colors.transparent,
                              selectedBorderWidth: 0.w,
                            ),
                            animationDuration: Duration.zero,
                            enableActiveFill: false,
                            enablePinAutofill: true,
                            textStyle: TextStyle(
                                color: Colors.white,
                                fontSize: 38.sp,
                                fontWeight: FontWeight.w400
                            ),
                            // backgroundColor: Colors.yellow,
                            controller: passwordController,
                            onCompleted: (v) {
                            },
                            onChanged: (value) {
                              setState(() {
                                password = value;
                              });
                              getIsDone();
                            },
                            beforeTextPaste: (text) {
                              //if you return true then it will show the paste confirmation dialog. Otherwise if false, then nothing will happen.
                              //but you can show anything you want here, like your pop up saying wrong paste format or etc
                              return true;
                            }, appContext: context,
                          ),
                        ),


                      ],
                    ),
                  ),
                  SizedBox(height: 32.w,),
                  GestureDetector(
                    onTap: (){
                      FocusScope.of(context).requestFocus(FocusNode());
                      _getMsgCode();
                    },
                    child: Container(
                      alignment: Alignment.centerRight,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Text('Resend'.tr,style: TextStyle(
                              color: Color(0xff666666),
                              fontSize: 28.sp,
                              fontWeight: FontWeight.w600
                          ),),
                          SizedBox(width: 10.w,),
                          Visibility(child: Text('${_countdownNum}s',style: TextStyle(
                              color: Colors.white,
                              fontSize: 28.sp,
                              fontWeight: FontWeight.w600
                          ),),visible: _countdownNum<60,)
                        ],
                      ),
                    ),
                  ),

                  SizedBox(height: 64.w,),
                  GestureDetector(
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                      getIsDone();
                      if(isDone==false){
                        return;
                      }
                      _login();
                    },
                    child: Container(
                      height: 108.w,
                      width: 670.w,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: isDone? themeColor:themeBlueDisableColor,
                          borderRadius: BorderRadius.circular(8.w)
                      ),
                      child: Text('Continue'.tr,style: TextStyle(
                          color: Colors.white,
                          fontSize: 28.sp,
                          fontWeight: FontWeight.w600
                      ),),
                    ),
                  ),
                  Expanded(child: GestureDetector(
                    onTap: (){
                      FocusScope.of(context).requestFocus(FocusNode());
                      getIsDone();
                      FocusScope.of(context).requestFocus(FocusNode());
                    },
                    child: Container(
                      color: Colors.transparent,
                      width: 1.sw,
                    ),
                  )),
                  Visibility(visible: true,child: Column(
                    children: [
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 48.w),
                        height: 48.w,
                        child: Stack(
                          children: [
                            Center(child: Container(
                              height: 1.w,
                              width: 480.w,
                              color: Color(0xff484848),
                            ),),
                            Center(
                              child: Container(
                                alignment: Alignment.center,
                                height: 48.w,
                                width: 48.w,
                                decoration: BoxDecoration(
                                    color: Color(0xff484848),
                                    borderRadius: BorderRadius.circular(48.w)
                                ),
                                child: Text('or',style: TextStyle(
                                    color: Color(0xff939393),
                                    fontSize: 24.sp
                                ),),
                              ),
                            )
                          ],
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 32.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Visibility(visible: true,child: GestureDetector(
                              onTap: ()async{
                                FocusScope.of(context).requestFocus(FocusNode());
                                _loginAPPByGoogle();
                              },
                              child: Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                    color: Color(0xff2B2B2B),
                                    borderRadius: BorderRadius.circular(92.w)
                                ),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Image.asset('assets/login/login_google.png',width: 40.w,),
                                  ],
                                ),
                              ),
                            ),),
                            SizedBox(width: 64.w,),
                            Visibility(visible: true,child: GestureDetector(
                              onTap: ()async{
                                FocusScope.of(context).requestFocus(FocusNode());
                                _loginAppByMsal();
                              },
                              child: Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                    color: Color(0xff2B2B2B),
                                    borderRadius: BorderRadius.circular(92.w)
                                ),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Image.asset('assets/login/login_wr.png',width: 40.w,),
                                  ],
                                ),
                              ),
                            ),),
                            Visibility(visible: Platform.isIOS,child: GestureDetector(
                              onTap: ()async{
                                FocusScope.of(context).requestFocus(FocusNode());
                                _loginAPPByApple();
                              },
                              child: Container(
                                width: 92.w,
                                height: 92.w,
                                margin: EdgeInsets.only(left: 64.w),
                                decoration: BoxDecoration(
                                    color: Color(0xff2B2B2B),
                                    borderRadius: BorderRadius.circular(92.w)
                                ),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Image.asset('assets/login/login_apple.png',width: 40.w,),
                                  ],
                                ),
                              ),
                            ),),
                          ],
                        ),
                      )
                    ],
                  ),),
                  SizedBox(height: 84.w,),
                  Container(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        GestureDetector(
                          onTap: (){
                            FocusScope.of(context).requestFocus(FocusNode());
                            Navigator.of(context).pushNamed('RegisterPage');
                          },
                          child: Container(
                            child: Text('Create an account'.tr,style: TextStyle(
                                color: Color(0xff576EFF),
                                fontSize: 28.sp,
                                fontWeight: FontWeight.w600
                            ),),
                          ),
                        ),
                        Container(
                          width: 6.w,
                          height: 6.w,
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(6.w)
                          ),
                          margin: EdgeInsets.symmetric(horizontal: 20.w),
                        ),
                        GestureDetector(
                          onTap: (){
                            FocusScope.of(context).requestFocus(FocusNode());
                            Navigator.of(context).pushNamed('ForgetPwd',arguments: 1);
                          },
                          child: Container(
                            child: Text('Fogot your password？'.tr,style: TextStyle(
                                color: Color(0xff576EFF),
                                fontSize: 28.sp,
                                fontWeight: FontWeight.w600
                            ),),
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(height: ScreenUtil().bottomBarHeight > 0? ScreenUtil().bottomBarHeight+20.w:48.w,),

                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
